package cn.iotab.iotkit.transport.api.access.handler.impl;

import cn.iotab.iotkit.transport.api.access.TransportAccessService;
import cn.iotab.iotkit.transport.api.access.handler.DeviceSessionOps;
import cn.iotab.iotkit.transport.api.access.handler.session.Session;
import cn.iotab.iotkit.transport.api.access.handler.support.ToTransportMessageSender;
import cn.iotab.iotkit.transport.api.common.message.msg.down.CloseSessionCmd;
import cn.iotab.iotkit.transport.api.common.queue.SendResultCallback;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class DefaultDeviceSessionOps implements DeviceSessionOps {

    private final DefaultDeviceSessionManager sessionManager;
    private final ToTransportMessageSender sender;

    public DefaultDeviceSessionOps(DefaultDeviceSessionManager sessionManager,
                                   TransportAccessService accessService) {
        this.sessionManager = sessionManager;
        this.sender = new ToTransportMessageSender(accessService);
    }

    @Override
    public void disconnect(String sessionId, CloseSessionCmd cmd) {
        sender.sendCloseSessionCmd(sessionId, cmd, new SendResultCallback<Void>() {
            @Override
            public void onSuccess(Void msg) {
                log.trace("message {} send success", cmd);
            }

            @Override
            public void onError(Throwable e) {
                log.warn("send closeSessionCmd failed, payload: {}", cmd.getMessage(), e);
            }
        });
    }

    @Override
    public void disconnect(String productKey, String deviceId, CloseSessionCmd cmd) {
        Session session = sessionManager.getSessionByDevice(productKey, deviceId);
        if (session != null) {
            disconnect(session.getSessionId(), cmd);
        } else {
            log.warn("device not online, ignore closeSessionCmd: {}", cmd.getMessage());
        }
    }
}
